﻿using System;
using System.Web;

namespace dPet.Infrastructure.Logging.Implementation
{
	using Hangerd.Mongodb;

	public class LoginLoggingService : ILoginLoggingService
	{
		private const string LOGINLOG_DBNAME = "dPet_LoginLog";
		private const string TABLENAME_FORMAT = "Log_{0}";

		private readonly IMongodbInsertService _mongodbInsertService;

		public LoginLoggingService(IMongodbInsertService mongodbInsertService)
		{
			_mongodbInsertService = mongodbInsertService;
		}

		public void AddLog(string loginName, HttpRequestBase request)
		{
			var loginLog = new LoginLog
			{
				ApplicationName = string.Empty,//todo: ApplicationName
				LoginName = loginName
			};

			if (request != null)
			{
				loginLog.IpAddress = request.UserHostAddress;
				loginLog.UserAgent = request.UserAgent;
			}

			var item = new MongodbItem
			{
				DatabaseName = LOGINLOG_DBNAME,
				TableName = string.Format(TABLENAME_FORMAT, DateTime.Now.ToString("yyyyMM")),
				Data = loginLog
			};

			_mongodbInsertService.Insert(item);
		}
	}
}
